<template>
  <div class="health-report-container">
    <div class="app-container">
      <!-- 时间选择器和健康评分 -->
            <!-- 时间选择器和健康评分 -->
      <el-row :gutter="20" class="header-section">
        <el-col :xs="24" :sm="24" :md="8" :lg="8">
          <div class="overview-score">
            <div class="score-content" :class="getScoreClass(healthScore)">
              <div class="score-label">整体健康评分</div>
              <div class="score-value">
                <span class="score-number">{{ healthScore }}</span>
                <span class="score-change" :class="scoreChangeClass"><i :class="scoreChangeIcon"></i> {{ Math.abs(scoreChange) }}</span>
              </div>
              <div class="score-note">{{ scoreNote }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="16" :lg="16">
          <div class="time-filter">
            <div class="filter-header">
              <h3 class="filter-title">时间范围</h3>
            </div>
            <div class="filter-buttons">
              <el-button
                size="small"
                :type="activeFilter === '7days' ? 'primary' : ''"
                @click="setTimeFilter('7days')"
                plain>
                <i class="el-icon-date"></i> 近7天
              </el-button>
              <el-button
                size="small"
                :type="activeFilter === '30days' ? 'primary' : ''"
                @click="setTimeFilter('30days')"
                plain>
                <i class="el-icon-date"></i> 近30天
              </el-button>
              <el-button
                size="small"
                :type="activeFilter === '3months' ? 'primary' : ''"
                @click="setTimeFilter('3months')"
                plain>
                <i class="el-icon-date"></i> 近3个月
              </el-button>
              <el-button
                size="small"
                :type="activeFilter === '1year' ? 'primary' : ''"
                @click="setTimeFilter('1year')"
                plain>
                <i class="el-icon-date"></i> 近1年
              </el-button>
              <el-button
                size="small"
                :type="activeFilter === 'custom' ? 'primary' : ''"
                @click="setTimeFilter('custom')"
                plain>
                <i class="el-icon-setting"></i> 自定义
              </el-button>

              <!-- 自定义时间范围选择器 -->
              <div v-show="showCustomDateRange" class="custom-date-range">
                <el-date-picker
                  v-model="customStartDate"
                  type="date"
                  placeholder="开始日期"
                  size="small"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
                <span class="date-separator">至</span>
                <el-date-picker
                  v-model="customEndDate"
                  type="date"
                  placeholder="结束日期"
                  size="small"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-button
                  type="primary"
                  size="small"
                  @click="applyCustomDateRange"
                  class="apply-button">
                  应用
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>


      <!-- 关键指标趋势 -->
      <div class="metrics-trend">
        <el-row>
          <el-col :span="24">
            <h3 class="section-title">关键指标趋势</h3>
          </el-col>
        </el-row>

        <div class="health-indicators">
          <div
            class="health-card"
            v-for="metric in metrics"
            :key="metric.key"
            @click="showMetricDetail(metric)"
          >
            <div class="card-header">
              <div class="card-title">
                <h3>{{ metric.name }}</h3>
                <p>{{ metric.description }}</p>
              </div>
              <div class="card-icon" :class="metric.iconClass">
                <i :class="metric.icon"></i>
              </div>
            </div>

            <div class="card-body">
              <div class="metric-value">
                <span class="value">{{ metric.currentValue }}</span>
                <span class="unit">{{ metric.unit }}</span>
              </div>
              <div class="metric-status" :class="getStatusClassForCard(metric.trend)">
                <i :class="getTrendIcon(metric.trend)"></i>
                {{ metric.trendText }}
              </div>
            </div>

            <div class="chart-container">
              <div :ref="'chart' + metric.key" class="mini-chart"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 健康时间轴 -->
      <div class="health-timeline">
        <el-row>
          <el-col :span="24">
            <div class="timeline-header">
              <h3 class="section-title">健康指标时间轴</h3>
            </div>
            <p class="section-description">跟踪您的健康指标变化历程，了解各项指标随时间的发展趋势和相互影响</p>
          </el-col>
        </el-row>

        <div class="timeline-wrapper">
          <div class="timeline-container">
            <div class="timeline-line"></div>

            <div
              v-for="(event, index) in timelineEvents"
              :key="index"
              class="timeline-item"
              @click="showDetailModal(event.date)"
            >
              <div class="timeline-connector"></div>
              <div class="timeline-dot" :class="{ 'warning': event.card.abnormalMetrics && event.card.abnormalMetrics.length > 0 }">
              </div>

              <div class="timeline-content">
                <div class="timeline-date">
                  <el-tag size="small" type="primary">{{ event.date }}</el-tag>
                </div>
                <h4 class="timeline-title">{{ event.title }}</h4>
                <p class="timeline-description">{{ event.description }}</p>

                <div class="timeline-card" v-if="event.card">
                  <div class="card-content">
                    <div class="score-section" :class="getScoreClass(event.card.score)">
                      <div class="score-main">
                        <span class="score-value">{{ event.card.score }}</span>
                        <div class="score-change" :class="getScoreTrendClass(event.card.scoreChange)">
                          <i :class="getScoreTrendIcon(event.card.scoreChange)"></i>
                          {{ event.card.scoreChange !== 0 ? Math.abs(event.card.scoreChange) : 0 }}
                        </div>
                      </div>
                      <div class="score-label">健康评分</div>
                    </div>

                    <div class="card-details">
                      <div class="abnormal-metrics" v-if="event.card.abnormalMetrics.length > 0">
                        <div class="section-title">异常指标</div>
                        <div class="metrics-list">
                        <span
                          v-for="metric in event.card.abnormalMetrics"
                          :key="metric.key"
                          class="metric-tag warning">
                          {{ metric.name }}
                        </span>
                        </div>
                      </div>

                      <div class="recommendations" v-if="event.card.recommendations.length > 0">
                        <div class="section-title">改善建议</div>
                        <ul class="recommendations-list">
                          <li v-for="(rec, index) in event.card.recommendations" :key="index">
                            {{ rec }}
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>

      <!-- 健康洞察与建议 -->
      <el-row :gutter="15" class="health-insights">
        <el-col :span="24">
          <h3 class="section-title">健康洞察与建议</h3>
        </el-col>

        <el-col :xs="24" :sm="8">
          <el-card class="insight-card" shadow="never">
            <div class="insight-content">
              <div class="insight-icon success">
                <i class="fa fa-line-chart"></i>
              </div>
              <div class="insight-text">
                <h4>观察到的关联</h4>
                <p>数据显示，当您的睡眠时长增加时，血压有明显下降趋势。同时，步数增加的日子里，睡眠质量也有所提高。</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="8">
          <el-card class="insight-card" shadow="never">
            <div class="insight-content">
              <div class="insight-icon primary">
                <i class="fa fa-lightbulb-o"></i>
              </div>
              <div class="insight-text">
                <h4>个性化建议</h4>
                <p>基于您的健康趋势，建议优先改善睡眠质量，这将有助于降低血压。可以尝试在睡前30分钟进行轻度步行。</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="8">
          <el-card class="insight-card" shadow="never">
            <div class="insight-content">
              <div class="insight-icon primary">
                <i class="fa fa-heart"></i>
              </div>
              <div class="insight-text">
                <h4>心电图监测</h4>
                <p>您的心电图数据显示正常，建议继续保持规律作息，避免过度劳累和情绪激动。定期进行心电图检查以监测心脏健康。</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 指标详情模态框 -->
    <el-dialog
      :visible.sync="metricDetailVisible"
      :title="metricDetailData.name + ' 详情'"
      width="60%"
      :before-close="closeMetricDetail"
      class="metric-detail-dialog"
      append-to-body
    >
      <div class="dialog-content">
        <div class="metric-info">
          <div class="metric-description">{{ metricDetailData.description }}</div>
          <div class="normal-range" v-if="metricDetailData.normalRange">
            <span class="label">正常范围:</span>
            <span class="value">{{ metricDetailData.normalRange }}</span>
          </div>
        </div>
        <div class="chart-container-large">
          <div :ref="'detailChart' + metricDetailData.key" class="large-chart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>

      <div class="health-advice-modal" :class="getAdviceClass(metricDetailData.statusClass)">
        <div class="advice-header-modal">
          <i class="fa fa-lightbulb-o advice-icon-modal"></i>
          <h3 class="advice-title-modal">健康建议</h3>
        </div>
        <div class="advice-content-wrapper">
          <p class="advice-content-modal">{{ metricDetailData.recommendations }}</p>
          <div class="advice-highlight" v-if="metricDetailData.statusClass && metricDetailData.statusClass.includes('warning')">
            <i class="fa fa-exclamation-circle"></i>
            <span>请特别关注此指标，及时采取措施</span>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 详情模态框 -->
    <el-dialog
      :title="modalTitle"
      :visible.sync="dialogVisible"
      width="800px"
      :before-close="handleClose"
      class="health-detail-dialog"
    >
      <div v-if="selectedDetail" class="detail-content">
        <el-row :gutter="15">
          <el-col :span="24">
            <div class="detail-score">
              <div class="score-header">
                <span class="score-title">健康评分</span>
                <span class="score-value">{{ selectedDetail.score }}</span>
              </div>
              <el-progress
                :percentage="selectedDetail.score"
                :show-text="false"
                :stroke-width="10"
                :color="getScoreColor(selectedDetail.score)">
              </el-progress>
              <div class="score-date">{{ selectedDetail.date }}</div>
            </div>
          </el-col>

          <el-col :span="24">
            <h4 class="detail-section-title">
              <i class="el-icon-data-analysis"></i> 健康指标详情
            </h4>
            <div class="metrics-detail">
              <el-row :gutter="10">
                <el-col
                  :xs="24"
                  :sm="12"
                  :md="8"
                  v-for="metric in selectedDetail.metrics"
                  :key="metric.name"
                  class="metric-detail-item"
                >
                  <div class="metric-detail-card">
                    <div class="metric-header">
                      <span class="metric-name">{{ metric.name }}</span>
                      <span class="metric-status" :class="getStatusClass(metric.status)">
                        {{ metric.status }}
                      </span>
                    </div>
                    <div class="metric-value-container">
                      <span class="metric-value">{{ metric.value }}</span>
                    </div>
                    <div class="metric-change" :class="getTrendClass(metric.trend)">
                      <i :class="getTrendIcon(metric.trend)"></i> {{ Math.abs(metric.change) }}
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>

          <el-col :span="24">
            <h4 class="detail-section-title">
              <i class="el-icon-edit-outline"></i> 健康笔记
            </h4>
            <div class="detail-notes">
              <p>{{ selectedDetail.notes }}</p>
            </div>
          </el-col>

          <el-col :span="24">
            <h4 class="detail-section-title">
              <i class="el-icon-lightbulb"></i> 健康建议
            </h4>
            <div class="detail-recommendations">
              <ul>
                <li v-for="(rec, index) in selectedDetail.recommendations" :key="index">
                  <i class="el-icon-check"></i> {{ rec }}
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" plain size="small">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false" size="small">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as echarts from 'echarts'
import {getTimeBaseData} from "@/api/health/healthReport";

export default {
  name: 'TimeBase',
  data() {
    return {
      customerId:null,
      activeFilter: '7days',
      dialogVisible: false,
      modalTitle: '',
      selectedDetail: null,
      chartInstances: [],
      showCustomDateRange: false, // 控制自定义时间范围选择器的显示
      customStartDate: '', // 自定义开始日期
      customEndDate: '', // 自定义结束日期
      metrics: [],
      timelineEvents: [],
      detailedData: {},
      // 健康评分相关数据
      healthScore: 78,
      scoreChange: 3,
      scoreNote: '较上月有所改善',
      // 新增指标详情模态框相关数据
      metricDetailVisible: false,
      metricDetailData: {},
      metricDetailChartInstance: null,
      // 基础健康数据 - 同源数据
      baseHealthData: [
        {
          date: '8月28日',
          dateValue: '2025-08-28',
          score: 78,
          event: {
            title: '健康状况良好',
            description: '大部分指标处于正常范围，血压略高'
          },
          metrics: [
            {name: "心率", key: "heartRate", value: 72, unit: "bpm", status: "正常", trend: "stable", change: 0},
            {name: "血压", key: "bloodPressure", value: "135/85", unit: "mmHg", status: "轻度偏高", trend: "up", change: -2, systolic: 135, diastolic: 85},
            {name: "血糖", key: "bloodSugar", value: 5.6, unit: "mmol/L", status: "正常", trend: "stable", change: 0},
            {name: "血氧", key: "oxygen", value: 98, unit: "%", status: "正常", trend: "up", change: 0},
            {name: "睡眠", key: "sleep", value: 6.5, unit: "小时", status: "不足", trend: "up", change: 3},
            {name: "步数", key: "steps", value: 7842, unit: "步", status: "良好", trend: "down", change: -1},
            {name: "心电", key: "ecg", value: "正常", unit: "", status: "正常", trend: "stable", change: 0}
          ],
          notes: "今日整体健康状况良好，血压持续下降趋势，睡眠时长有所增加。建议继续保持当前的运动和饮食计划。",
          recommendations: [
            "继续保持低盐饮食，有助于血压进一步下降",
            "尝试提前15分钟入睡，目标达到7小时睡眠",
            "晚饭后可以增加15分钟散步，帮助提高睡眠质量"
          ]
        },
        {
          date: '8月21日',
          dateValue: '2025-08-21',
          score: 76,
          event: {
            title: '血压开始下降',
            description: '实施医生建议的低盐饮食和有氧运动后初见成效'
          },
          metrics: [
            {name: "心率", key: "heartRate", value: 73, unit: "bpm", status: "正常", trend: "stable", change: -3},
            {name: "血压", key: "bloodPressure", value: "136/86", unit: "mmHg", status: "轻度偏高", trend: "up", change: -2, systolic: 136, diastolic: 86},
            {name: "血糖", key: "bloodSugar", value: 5.6, unit: "mmol/L", status: "正常", trend: "stable", change: -0.1},
            {name: "血氧", key: "oxygen", value: 98, unit: "%", status: "正常", trend: "up", change: 1},
            {name: "睡眠", key: "sleep", value: 6.3, unit: "小时", status: "不足", trend: "up", change: 5},
            {name: "步数", key: "steps", value: 7900, unit: "步", status: "良好", trend: "down", change: -2},
            {name: "心电", key: "ecg", value: "正常", unit: "", status: "正常", trend: "stable", change: 0}
          ],
          notes: "实施低盐饮食一周后，血压开始出现下降趋势。睡眠质量也有所改善，可能与增加的傍晚散步有关。",
          recommendations: [
            "继续坚持每日30分钟有氧运动",
            "尝试睡前放松技巧，如冥想或深呼吸",
            "保持水分摄入，有助于维持正常血压"
          ]
        },
        {
          date: '8月14日',
          dateValue: '2025-08-14',
          score: 74,
          event: {
            title: '健康检查',
            description: '医生建议关注血压和睡眠问题'
          },
          metrics: [
            {name: "心率", key: "heartRate", value: 76, unit: "bpm", status: "正常", trend: "stable", change: -2},
            {name: "血压", key: "bloodPressure", value: "138/87", unit: "mmHg", status: "轻度偏高", trend: "down", change: -4, systolic: 138, diastolic: 87},
            {name: "血糖", key: "bloodSugar", value: 5.7, unit: "mmol/L", status: "正常", trend: "stable", change: -0.1},
            {name: "血氧", key: "oxygen", value: 97, unit: "%", status: "正常", trend: "stable", change: 1},
            {name: "睡眠", key: "sleep", value: 6.0, unit: "小时", status: "不足", trend: "stable", change: 3},
            {name: "步数", key: "steps", value: 8100, unit: "步", status: "良好", trend: "stable", change: -5},
            {name: "心电", key: "ecg", value: "轻度异常", unit: "", status: "注意", trend: "down", change: -1}
          ],
          notes: "健康检查显示血压轻度偏高，医生建议减少盐分摄入并增加有氧运动。睡眠时长仍然不足，需要调整作息时间。心电图检查显示轻度异常。",
          recommendations: [
            "开始实施低盐饮食计划",
            "每天安排30分钟有氧运动",
            "尝试晚上10点前入睡，建立规律作息",
            "定期复查心电图，关注心脏健康"
          ]
        },
        {
          date: '8月7日',
          dateValue: '2025-08-07',
          score: 72,
          event: {
            title: '血压有所上升',
            description: '工作压力增加，同时睡眠质量下降'
          },
          metrics: [
            {name: "心率", key: "heartRate", value: 78, unit: "bpm", status: "正常", trend: "up", change: 3},
            {name: "血压", key: "bloodPressure", value: "142/89", unit: "mmHg", status: "轻度偏高", trend: "up", change: 8, systolic: 142, diastolic: 89},
            {name: "血糖", key: "bloodSugar", value: 5.8, unit: "mmol/L", status: "正常", trend: "stable", change: 0.1},
            {name: "血氧", key: "oxygen", value: 96, unit: "%", status: "正常", trend: "stable", change: 0},
            {name: "睡眠", key: "sleep", value: 5.8, unit: "小时", status: "不足", trend: "down", change: -6},
            {name: "步数", key: "steps", value: 8500, unit: "步", status: "良好", trend: "up", change: 4},
            {name: "心电", key: "ecg", value: "正常", unit: "", status: "正常", trend: "stable", change: 0}
          ],
          notes: "工作压力增加导致血压上升，同时睡眠质量下降。步数有所增加，但未能抵消其他因素的负面影响。",
          recommendations: [
            "尝试工作间隙进行短暂放松",
            "减少咖啡因摄入，尤其是下午和晚上",
            "考虑睡前使用放松应用帮助入睡"
          ]
        },
        {
          date: '8月1日',
          dateValue: '2025-08-01',
          score: 75,
          event: {
            title: '基础健康评估',
            description: '开始记录健康指标，建立基准线'
          },
          metrics: [
            {name: "心率", key: "heartRate", value: 75, unit: "bpm", status: "正常", trend: "stable", change: 0},
            {name: "血压", key: "bloodPressure", value: "130/82", unit: "mmHg", status: "正常", trend: "stable", change: 0, systolic: 130, diastolic: 82},
            {name: "血糖", key: "bloodSugar", value: 5.7, unit: "mmol/L", status: "正常", trend: "stable", change: 0},
            {name: "血氧", key: "oxygen", value: 96, unit: "%", status: "正常", trend: "stable", change: 0},
            {name: "睡眠", key: "sleep", value: 6.2, unit: "小时", status: "不足", trend: "stable", change: 0},
            {name: "步数", key: "steps", value: 8200, unit: "步", status: "良好", trend: "stable", change: 0},
            {name: "心电", key: "ecg", value: "正常", unit: "", status: "正常", trend: "stable", change: 0}
          ],
          notes: "开始记录健康指标，建立基准线。睡眠时长略低于推荐水平，其他指标均在正常范围内。",
          recommendations: [
            "尝试增加每日睡眠时长至7小时",
            "保持当前的活动水平",
            "考虑建立规律的健康数据记录习惯"
          ]
        }
      ],

      // 指标配置
      metricConfigs: [
        {
          key: 'heartRate',
          id: 1,
          name: '心率',
          type: 'primary',
          icon: 'fa fa-heartbeat',
          iconClass: 'heart-rate',
          normalRange: '60-100 bpm',
          recommendations: '保持规律运动，避免过度劳累。如有心悸或胸闷症状，请及时就医。'
        },
        {
          key: 'bloodPressure',
          id: 2,
          name: '血压',
          type: 'primary',
          icon: 'fa fa-tint',
          iconClass: 'blood-pressure',
          normalRange: '收缩压 < 140 mmHg，舒张压 < 90 mmHg',
          recommendations: '减少盐分摄入，保持情绪稳定，定期监测血压变化。'
        },
        {
          key: 'bloodSugar',
          id: 3,
          name: '血糖',
          type: 'success',
          icon: 'fa fa-flask',
          iconClass: 'blood-sugar',
          normalRange: '空腹血糖 < 6.1 mmol/L',
          recommendations: '控制饮食，避免高糖食物，保持规律作息。'
        },
        {
          key: 'oxygen',
          id: 4,
          name: '血氧',
          type: 'success',
          icon: 'fa fa-moon-o',
          iconClass: 'oxygen-level',
          normalRange: '≥ 95%',
          recommendations: '保持室内空气流通，适当进行有氧运动。'
        },
        {
          key: 'sleep',
          id: 5,
          name: '睡眠',
          type: 'warning',
          icon: 'fa fa-bed',
          iconClass: 'sleep',
          normalRange: '7-9 小时',
          recommendations: '保持规律作息，睡前避免使用电子设备，创造良好睡眠环境。'
        },
        {
          key: 'steps',
          id: 6,
          name: '步数',
          type: 'primary',
          icon: 'fa fa-male',
          iconClass: 'steps',
          normalRange: '≥ 6000 步',
          recommendations: '每天保持适量运动，逐步增加步数目标，避免久坐。'
        },
        {
          key: 'ecg',
          id: 7,
          name: '心电',
          type: 'primary',
          icon: 'fa fa-heart',
          iconClass: 'heart-rate',
          normalRange: '正常',
          recommendations: '定期进行心电图检查，保持规律作息，避免过度劳累和情绪激动。'
        }
      ]

    }
  },
  created() {
    this.customerId = this.$route.params && this.$route.params.customerId

  },
  mounted() {
    this.$nextTick(() => {
      // 初始化时加载模拟数据
      this.loadData();
     // this.initCharts();
    });
  },

  beforeDestroy() {
    this.chartInstances.forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });

    // 销毁指标详情图表
    if (this.metricDetailChartInstance) {
      this.metricDetailChartInstance.dispose();
    }
  },
  computed: {
    scoreChangeClass() {
      return this.scoreChange > 0 ? 'success' : this.scoreChange < 0 ? 'down' : 'stable';
    },
    scoreChangeIcon() {
      if (this.scoreChange > 0) {
        return 'el-icon-top';
      } else if (this.scoreChange < 0) {
        return 'el-icon-bottom';
      } else {
        return 'el-icon-minus';
      }
    }
  },
  methods: {
    // 根据分数获取对应的类名
    getScoreClass(score) {
      if (score >= 80) {
        return 'high-score';
      } else if (score >= 60) {
        return 'medium-score';
      } else {
        return 'low-score';
      }
    },

    getScoreTrendIcon(scoreChange) {
      if (scoreChange > 0) {
        return 'el-icon-top';
      } else if (scoreChange < 0) {
        return 'el-icon-bottom';
      } else {
        return 'el-icon-minus';
      }
    },

    getScoreTrendClass(scoreChange) {
      if (scoreChange > 0) {
        return 'up'; // 分数提升为好，使用绿色
      } else if (scoreChange < 0) {
        return 'down'; // 分数下降为坏，使用红色
      } else {
        return 'stable';
      }
    },
    // 统一数据加载入口，后续只需要替换这个方法内的实现即可接入真实API
    async loadData() {
      // 当前使用模拟数据，后续替换为真实API调用
     // this.loadMockData();
     // return
      getTimeBaseData(this.customerId, this.activeFilter,{startDate: this.customStartDate, endDate: this.customEndDate}).then(res=>{
        this.baseHealthData = res.data.baseHealthData;
        this.metricConfigs = res.data.metricConfigs;
        // 根据基础健康数据生成各部分数据
        this.generateMetricsData();
        this.generateTimelineEvents();
        this.generateDetailedData();

        // 加载完成后重新初始化图表
        this.$nextTick(() => {
          this.disposeCharts();
          this.initCharts();
        });
      })
    },

    // 加载模拟数据
    loadMockData() {
      // 根据基础健康数据生成各部分数据
      this.generateMetricsData();
      this.generateTimelineEvents();
      this.generateDetailedData();

      // 加载完成后重新初始化图表
      this.$nextTick(() => {
        this.disposeCharts();
        this.initCharts();
      });

    },

    // 生成关键指标趋势数据
    generateMetricsData() {
      this.metrics = this.metricConfigs.map(config => {
        // 获取该指标在所有日期的数据
        const metricData = this.baseHealthData.map(dayData => {
          const metric = dayData.metrics.find(m => m.key === config.key);
          return {
            ...metric,
            date: dayData.date
          };
        });
        // 获取最新数据（数组第一个元素）
        const latestMetric = metricData[metricData.length-1];

        // if(metricData&&metricData.length>1){
        //   const latestMetric2 = metricData[metricData.length-2];
        //   const metricChange = Number(latestMetric.value) - Number(latestMetric2.value);
        //   latestMetric.change = metricChange;
        //   latestMetric.trend = metricChange===0?0:metricChange>0?'up':'down';
        // }
        // 构造图表数据
        let chartData = {};
        if (config.key === 'bloodPressure') {
          // 血压特殊处理
          chartData = {
            xData: metricData.map(item => item.date),
            systolic: metricData.map(item => item.systolic),
            diastolic: metricData.map(item => item.diastolic)
          };
        } else if (config.key === 'ecg') {
          // 心电图特殊处理 - 使用数值表示心电图状态
          // 正常: 100, 轻度异常: 60, 中度异常: 30, 严重异常: 0
          const ecgValues = metricData.map(item => {
            switch(item.value) {
              case '正常': return 100;
              case '轻度异常': return 60;
              case '中度异常': return 30;
              case '严重异常': return 0;
              default: return 100;
            }
          });

          chartData = {
            xData: metricData.map(item => item.date),
            yData: ecgValues
          };
        }  else {
          // 其他指标
          chartData = {
            xData: metricData.map(item => item.date),
            yData: metricData.map(item => item.value)
          };
        }

        return {
          key: config.key,
          name: config.name,
          type: config.type,
          icon: config.icon,
          iconClass: config.iconClass,
          description: metricData?this.getMetricDescription(metricData):'',
          currentValue: latestMetric?this.getMetricCurrentValue(latestMetric, config.key):0,
          unit: config.unit,
          trend: latestMetric?latestMetric.trend:'stable',
          trendText: latestMetric?this.getMetricTrendText(latestMetric.trend, config.key):'',
          chartData: chartData,
          normalRange: config.normalRange,
          recommendations: config.recommendations,
          statusClass: latestMetric?this.getStatusClass(latestMetric.status):''
        };
      });
    },

    // 生成时间轴数据
    generateTimelineEvents() {
      this.timelineEvents = this.baseHealthData.reverse().map(healthData => {
        return {
          date: healthData.date,
          title: healthData.event.title,
          description: healthData.event.description,
          card: this.generateTimelineCard(healthData)
        };
      });
    },

    // 生成时间轴卡片 - 根据健康数据动态生成
    generateTimelineCard(healthData) {
      // 计算健康评分变化
      const scoreChange = this.calculateScoreChange(healthData.date, healthData.score);

      // 获取异常指标
      const abnormalMetrics = healthData.metrics.filter(metric =>
        metric.status.includes('偏高') || metric.status.includes('偏低') || metric.status.includes('不足')
      );

      // 获取改善建议
      const recommendations = healthData.recommendations.slice(0, 2); // 只取前两条建议

      // 构建卡片内容
      const card = {
        score: healthData.score,
        scoreChange: scoreChange,
        abnormalMetrics: abnormalMetrics,
        recommendations: recommendations,
        trend: scoreChange > 0 ? 'up' : scoreChange < 0 ? 'down' : 'stable'
      };

      return card;
    },

    // 计算健康评分变化
    calculateScoreChange(currentDate, currentScore) {
      // 查找上一个日期的数据
      const currentIndex = this.baseHealthData.findIndex(data => data.date === currentDate);
      if (currentIndex < this.baseHealthData.length - 1) {
        const previousScore = this.baseHealthData[currentIndex + 1].score;
        return currentScore - previousScore;
      }
      return 0;
    },

    // 生成详细数据
        // 生成详细数据
    generateDetailedData() {
      this.detailedData = {};
      // 使用最新的健康数据来设置主评分
      if (this.baseHealthData.length > 0) {
        const latestData = this.baseHealthData[0];
        this.healthScore = latestData.score;
        this.scoreNote = latestData.event.description;

        // 计算评分变化
        if (this.baseHealthData.length > 1) {
          const previousScore = this.baseHealthData[1].score;
          this.scoreChange = this.healthScore - previousScore;
        } else {
          this.scoreChange = 0;
        }
      }

      this.baseHealthData.forEach(data => {
        this.detailedData[data.date] = {
          date: this.formatDate(data.dateValue),
          score: data.score,
          metrics: data.metrics.map(metric => ({
            name: metric.name,
            value: `${metric.value} ${metric.unit}`,
            status: metric.status,
            trend: metric.trend,
            change: metric.change
          })),
          notes: data.notes,
          recommendations: data.recommendations
        };
      });
    },


    // 获取指标描述
    getMetricDescription(metricData) {
      // 简化处理，实际可根据数据变化情况生成更准确的描述
      const trends = metricData.map(data => data.trend);
      if (trends.every(t => t === 'stable')) {
        return '近期趋势稳定';
      } else if (trends.some(t => t === 'up')) {
        return '近期有所改善';
      } else if (trends.some(t => t === 'down')) {
        return '近期有所下降';
      }
      return '近期趋势稳定';
    },

    // 获取当前值
    getMetricCurrentValue(latestMetric, key) {
      // 步数需要格式化
      if (key === 'steps') {
        return this.formatNumber(latestMetric.value);
      }
      return latestMetric.value;
    },

    // 获取趋势文本
    getMetricTrendText(trend, key) {
      switch (trend) {
        case 'up':
          // 对于不同指标，上升可能代表好或坏
          if (key === 'bloodPressure' || key === 'sleep' || key === 'steps') {
            return key === 'bloodPressure' ? '下降' : '增加';
          }
          return '上升';
        case 'down':
          if (key === 'bloodPressure' || key === 'sleep' || key === 'steps') {
            return key === 'bloodPressure' ? '上升' : '减少';
          }
          return '下降';
        default:
          return '稳定';
      }
    },

    // 格式化数字（添加千位分隔符）
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}年${month}月${day}日`;
    },

    // 销毁现有图表
    disposeCharts() {
      this.chartInstances.forEach(chart => {
        if (chart) {
          chart.dispose();
        }
      });
      this.chartInstances = [];
    },

    getScoreColor(score) {
      if (score >= 80) {
        return '#13ce66'; // 绿色
      } else if (score >= 60) {
        return '#ffba00'; // 橙色
      } else {
        return '#ff4949'; // 红色
      }
    },
    setTimeFilter(filter) {
      this.activeFilter = filter
      if (filter === 'custom') {
        this.showCustomDateRange = true
      } else {
        this.showCustomDateRange = false
        // 后续可以在这里添加根据时间范围加载数据的逻辑
         this.loadData();
      }
    },
    applyCustomDateRange() {
      if (this.customStartDate && this.customEndDate) {
        // 后续可以在这里添加根据自定义时间范围加载数据的逻辑
        // this.loadData(this.customStartDate, this.customEndDate);
        console.log('应用自定义时间范围:', this.customStartDate, '至', this.customEndDate)
      } else {
        this.$message.warning('请选择完整的日期范围')
      }
    },
    showDetailModal(date) {
      this.selectedDetail = this.detailedData[date]
      if (this.selectedDetail) {
        this.modalTitle = `${date} 健康详情`
        this.dialogVisible = true
      }
    },

    handleClose(done) {
      done()
      /* this.$confirm('确认关闭详情窗口?')
         .then(_ => {
           done()
         })
         .catch(_ => {})*/
    },

    getTrendIcon(trend) {
      switch (trend) {
        case 'up':
          return 'el-icon-top'
        case 'down':
          return 'el-icon-bottom'
        case 'stable':
          return 'el-icon-minus'
        default:
          return 'el-icon-minus'
      }
    },

    getStatusClass(status) {
      if (!status) return ''
      if (status.includes('正常')) return 'success'
      if (status.includes('偏高') || status.includes('不足')|| status.includes('偏低')) return 'warning'
      if (status.includes('异常')) return 'danger'
      return ''
    },

    getStatusClassForCard(trend) {
      switch (trend) {
        case 'up':
          return 'status-success'
        case 'down':
          return 'status-warning'
        case 'stable':
          return 'status-success'
        default:
          return 'status-success'
      }
    },

    getTrendClass(trend) {
      switch (trend) {
        case 'up':
          return 'success'
        case 'down':
          return 'danger'
        case 'stable':
          return 'neutral'
        default:
          return ''
      }
    },

    initCharts() {
      this.metrics.forEach(metric => {
        const chartRef = this.$refs['chart' + metric.key];
        if (chartRef && chartRef.length > 0) {
          const chartInstance = echarts.init(chartRef[0]);
          this.chartInstances.push(chartInstance);

          let option;
          const commonXAxisConfig = {
            type: 'category',
            show: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#ccc'
              }
            },
            axisTick: {
              show: true,
              lineStyle: {
                color: '#ccc'
              }
            },
            axisLabel: {
              show: true,
              fontSize: 8,
              color: '#999',
              rotate: 45
            },
            boundaryGap: false,
            data: metric.chartData.xData
          };

          const commonGridConfig = {
            left: '10',
            right: '10',
            top: '20',
            bottom: '30'
          };

          if (metric.key === 'bloodPressure') { // 血压图表（特殊处理，包含收缩压和舒张压）
            option = {
              grid: commonGridConfig,
              xAxis: commonXAxisConfig,
              yAxis: {
                show: false,
                type: 'value'
              },
              series: [
                {
                  name: '收缩压',
                  type: 'line',
                  showSymbol: true,
                  symbolSize: 6,
                  smooth: true,
                  lineStyle: {
                    width: 2,
                    color: '#F87272'
                  },
                  data: metric.chartData.systolic || [],
                  areaStyle: null,
                  label: {
                    show: true,
                    position: 'top',
                    fontSize: 10,
                    color: '#F87272',
                    formatter: '{c}',
                    distance: 5
                  }
                },
                {
                  name: '舒张压',
                  type: 'line',
                  showSymbol: true,
                  symbolSize: 6,
                  smooth: true,
                  lineStyle: {
                    width: 2,
                    color: '#FB923C'
                  },
                  data: metric.chartData.diastolic || [],
                  areaStyle: null,
                  label: {
                    show: true,
                    position: 'bottom',
                    fontSize: 10,
                    color: '#FB923C',
                    formatter: '{c}',
                    distance: 5
                  }
                }
              ],
              tooltip: {
                show: true,
                trigger: 'axis'
              },
              legend: {
                show: false
              }
            };
          } else { // 其他指标图表
            option = {
              grid: commonGridConfig,
              xAxis: commonXAxisConfig,
              yAxis: {
                show: false,
                type: 'value'
              },
              series: [{
                name: metric.name,
                type: 'line',
                smooth: true,
                showSymbol: true,
                symbolSize: 6,
                lineStyle: {
                  color: this.getLineColor(metric.type),
                  width: 2
                },
                areaStyle: {
                  color: this.getAreaColor(metric.type)
                },
                data: metric.chartData.yData,
                label: {
                  show: true,
                  position: 'top',
                  fontSize: 10,
                  color: this.getLineColor(metric.type),
                  formatter: (params) => {
                    // 心电图特殊处理 - 显示文字而不是数值
                    if (metric.key === 'ecg') {
                      const index = params.dataIndex;
                      const originalValue = metric.chartData.yData[index];
                      if (originalValue === 100) return '正常';
                      if (originalValue === 60) return '轻度异常';
                      if (originalValue === 30) return '中度异常';
                      if (originalValue === 0) return '严重异常';
                      return '正常';
                    }
                    return params.value;
                  },
                  distance: 5
                }
              }],
              tooltip: {
                show: true,
                trigger: 'axis',
                formatter: (params) => {
                  // 心电图特殊处理 - 显示文字而不是数值
                  if (metric.key === 'ecg') {
                    const param = params[0];
                    const index = param.dataIndex;
                    const originalValue = metric.chartData.yData[index];
                    let statusText = '正常';
                    if (originalValue === 100) statusText = '正常';
                    else if (originalValue === 60) statusText = '轻度异常';
                    else if (originalValue === 30) statusText = '中度异常';
                    else if (originalValue === 0) statusText = '严重异常';

                    return `${param.name}<br/>${param.seriesName}: ${statusText}`;
                  }
                  return params[0].name + '<br/>' + params.map(param =>
                    `${param.seriesName}: ${param.value}`
                  ).join('<br/>');
                }
              }
            };
          }

          chartInstance.setOption(option);
        }
      });
    },

    getLineColor(type) {
      const colorMap = {
        'primary': '#1890ff',
        'success': '#13ce66',
        'warning': '#ffba00'
      };
      return colorMap[type] || '#1890ff';
    },

    getAreaColor(type) {
      const colorMap = {
        'primary': 'rgba(24, 144, 255, 0.1)',
        'success': 'rgba(19, 206, 102, 0.1)',
        'warning': 'rgba(255, 186, 0, 0.1)'
      };
      return colorMap[type] || 'rgba(24, 144, 255, 0.1)';
    },

    // 显示指标详情
    showMetricDetail(metric) {
      this.metricDetailData = metric;
      this.metricDetailVisible = true;

      this.$nextTick(() => {
        this.initDetailChart(metric);
      });
    },

    // 初始化详情图表
    initDetailChart(metric) {
      // 销毁之前的图表实例
      if (this.metricDetailChartInstance) {
        this.metricDetailChartInstance.dispose();
      }

      const chartRef = this.$refs['detailChart' + metric.key];
      if (chartRef) {
        this.metricDetailChartInstance = echarts.init(chartRef);

        let option;
        const commonXAxisConfig = {
          type: 'category',
          show: true,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ccc'
            }
          },
          axisTick: {
            show: true,
            lineStyle: {
              color: '#ccc'
            }
          },
          axisLabel: {
            show: true,
            fontSize: 12,
            color: '#666'
          },
          boundaryGap: false,
          data: metric.chartData.xData
        };

        const commonGridConfig = {
          left: '40',
          right: '20',
          top: '50',  // 增加顶部边距，避免标题遮挡
          bottom: '40'
        };

        if (metric.key === 'bloodPressure') { // 血压图表（特殊处理，包含收缩压和舒张压）
          option = {
            title: {
              text: '血压变化趋势',
              textStyle: {
                fontSize: 16,
                fontWeight: 'bold'
              },
              left: 'center',
              top: '10'  // 设置标题位置
            },
            grid: commonGridConfig,
            xAxis: commonXAxisConfig,
            yAxis: {
              type: 'value',
              name: 'mmHg',
              nameLocation: 'middle',
              nameGap: 30,
              axisLine: {
                show: true
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed'
                }
              }
            },
            series: [
              {
                name: '收缩压',
                type: 'line',
                showSymbol: true,
                symbolSize: 8,
                smooth: true,
                lineStyle: {
                  width: 3,
                  color: '#F87272'
                },
                data: metric.chartData.systolic || [],
                areaStyle: null,
                label: {
                  show: true,
                  position: 'top',
                  fontSize: 12,
                  color: '#F87272',
                  formatter: '{c}',
                  distance: 5
                }
              },
              {
                name: '舒张压',
                type: 'line',
                showSymbol: true,
                symbolSize: 8,
                smooth: true,
                lineStyle: {
                  width: 3,
                  color: '#FB923C'
                },
                data: metric.chartData.diastolic || [],
                areaStyle: null,
                label: {
                  show: true,
                  position: 'bottom',
                  fontSize: 12,
                  color: '#FB923C',
                  formatter: '{c}',
                  distance: 5
                }
              }
            ],
            tooltip: {
              show: true,
              trigger: 'axis'
            },
            legend: {
              show: true,
              top: 'bottom'
            }
          };
        } else { // 其他指标图表
          option = {
            title: {
              text: metric.name + '变化趋势',
              textStyle: {
                fontSize: 16,
                fontWeight: 'bold'
              },
              left: 'center',
              top: '10'  // 设置标题位置
            },
            grid: commonGridConfig,
            xAxis: commonXAxisConfig,
            yAxis: {
              type: 'value',
              name: metric.unit,
              nameLocation: 'middle',
              nameGap: 30,
              axisLine: {
                show: true
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed'
                }
              }
            },
            series: [{
              name: metric.name,
              type: 'line',
              smooth: true,
              showSymbol: true,
              symbolSize: 8,
              lineStyle: {
                color: this.getLineColor(metric.type),
                width: 3
              },
              areaStyle: {
                color: this.getAreaColor(metric.type)
              },
              data: metric.chartData.yData,
              label: {
                show: true,
                position: 'top',
                fontSize: 12,
                color: this.getLineColor(metric.type),
                formatter: (params) => {
                  // 心电图特殊处理 - 显示文字而不是数值
                  if (metric.key === 'ecg') {
                    const index = params.dataIndex;
                    const originalValue = metric.chartData.yData[index];
                    if (originalValue === 100) return '正常';
                    if (originalValue === 60) return '轻度异常';
                    if (originalValue === 30) return '中度异常';
                    if (originalValue === 0) return '严重异常';
                    return '正常';
                  }
                  return params.value;
                },
                distance: 5
              }
            }],
            tooltip: {
              show: true,
              trigger: 'axis',
              formatter: (params) => {
                // 心电图特殊处理 - 显示文字而不是数值
                if (metric.key === 'ecg') {
                  const param = params[0];
                  const index = param.dataIndex;
                  const originalValue = metric.chartData.yData[index];
                  let statusText = '正常';
                  if (originalValue === 100) statusText = '正常';
                  else if (originalValue === 60) statusText = '轻度异常';
                  else if (originalValue === 30) statusText = '中度异常';
                  else if (originalValue === 0) statusText = '严重异常';

                  return `${param.name}<br/>${param.seriesName}: ${statusText}`;
                }
                return params[0].name + '<br/>' + params.map(param =>
                  `${param.seriesName}: ${param.value}`
                ).join('<br/>');
              }
            }
          };
        }

        this.metricDetailChartInstance.setOption(option);
      }
    },

    // 关闭指标详情模态框
    closeMetricDetail() {
      this.metricDetailVisible = false;
      if (this.metricDetailChartInstance) {
        this.metricDetailChartInstance.dispose();
        this.metricDetailChartInstance = null;
      }
    },

    // 获取建议类名
    getAdviceClass(statusClass) {
      if (statusClass && statusClass.includes('warning')) {
        return 'advice-warning';
      } else if (statusClass && statusClass.includes('success')) {
        return 'advice-success';
      }
      return 'advice-normal';
    },
    // 获取日期首字母
    getFirstLetter(date) {
      if (date && date.length > 0) {
        return date.charAt(0);
      }
      return '';
    }
  }
}
</script>

<style scoped src="@/views/customer/health/scss/timeBase.css"></style>
